package com.ctn.information.content;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.R.integer;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Gallery;
import android.widget.ImageView;

import com.ctn.information.MainActivity;
import com.ctn.information.R;
import com.ctn.information.adapter.NewsListAdapter;
import com.ctn.information.adapter.SycnImageAdapter;
import com.ctn.information.adapter.ViewPagerAdapter;
import com.ctn.information.entity.Information;
import com.ctn.information.entity.SwitchImageInfo;
import com.ctn.information.util.Files;
import com.ctn.information.util.Net;
import com.ctn.information.util.SwitchFragmentUtil;
import com.ctn.information.view.xlistview.XListView;
import com.ctn.information.view.xlistview.XListView.IXListViewListener;

/**
 * 中心区域面板 - 上拉刷新下拉更多示例
 * 
 * @author HLJ
 *
 */
public class SampleFragment extends Fragment implements IXListViewListener{



    private com.ctn.information.view.xlistview.XListView mListView;
	private NewsListAdapter mAdapter;
	private List<Information> items = new ArrayList<Information>();
	private List<SwitchImageInfo> images = new ArrayList<SwitchImageInfo>();
	
	final Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            // switch (msg.what) {
            // case 1:
            //
            // break;
            // }
            super.handleMessage(msg);
           // 切换当前显示的图片

            
        }
    };
	private int start = 0;
	private static int refreshCnt = 0;
	private int num = 0;
	private Context mContext;
	List<String> urls = new ArrayList<String>(); // 所有图片地址List
	List<String> url = new ArrayList<String>(); // 需要下载图片的url地址
	public static SycnImageAdapter imageAdapter;
	private Gallery images_ga;
	public static HashMap<String, Bitmap> imagesCache = new HashMap<String, Bitmap>(); // 图片缓存
	String secondMenuId="";
	
	/**
     * 这里定义了相册的总数100条.
     */
    private static final int ALBUM_COUNT = 100;



    private ViewPager mViewPager;

    /**
     * 适配器.
     */
    private ViewPagerAdapter mViewPagerAdapter;


    static private ScheduledExecutorService scheduledExecutorService;

    private int currentItem = 0; // 当前图片的索引号

    private List<ImageView> imageViews; // 滑动的图片集合

    private class ScrollTask implements Runnable {

        public void run() {
            synchronized (mViewPager) {
                
                mHandler.obtainMessage().sendToTarget(); // 通过Handler切换图片
            }
        }

    }
	
	
	public SampleFragment() { 
	}
	
	private void geneItems() {
		//===2013-5-27===edit ==start
		/*
		for (int i = 0; i != 20; ++i) {
			Information info=new Information();
			info.setId(String.valueOf(i));
			info.setImageUrl("http://s0.hao123img.com/res/r/image/2013-05-24/3e3072ded1145af932c3240f164d4302.jpg");
//			info.setImageUrl("");
			info.setNewsTitle("title"+i);
			info.setNewsContent("content"+i);
			info.setTimeStemp(new Date());
			items.add(info);
		}*/
		
//		SharedPreferences prefer=getActivity().getSharedPreferences("CurrentSecondMenuItem", Context.MODE_PRIVATE);
		Bundle b = this.getArguments();
		secondMenuId =  (String)b.getString("SecondTopic");
		//secondMenuId=prefer.getString("SecondMenuId", "");
		//发送 secondMenuId 到后台 获取网络请求获取数据得到 jsonStr
				/*
				 * 预留网络接口方法
				 */
		String jsonStr="{total:10,success:'true', informations:[{ id:'1', title:'信息标题',image:'http://127.0.0.1:8080/xx.png',addtime:'2013-05-20 11:11:11', memo :'xxxxxxxxx'},{ id:'1', title :'信息标题2',image:'http://127.0.0.1:8080/xx.png',addtime:'2013-05-20 11:11:11', memo :'xxxxxxxxx'}]}";
		try {
			JSONObject data =new JSONObject(jsonStr);
			if(null!=jsonStr){
				if(data.get("success").equals("true")){
					JSONArray dataDetails =data.getJSONArray("informations");
					if(null!=dataDetails&& dataDetails.length()>0){
						for (int i = 0; i < dataDetails.length(); i++) {
							Information info=new Information();
							info.setId(dataDetails.getJSONObject(i).get("id").toString());
							info.setImageUrl(dataDetails.getJSONObject(i).getString("image"));
							//info.setNewsTitle(dataDetails.getJSONObject(i).getString("title"));
							/*
							 * 测试内容，实际运行时换成上面那句
							 */
							info.setNewsTitle(dataDetails.getJSONObject(i).getString("title")+secondMenuId);
							info.setNewsContent(dataDetails.getJSONObject(i).getString("memo"));
							try {
								info.setTimeStemp(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dataDetails.getJSONObject(i).getString("addtime")));
							} catch (ParseException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							items.add(info);
						}
					}
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//===2013-5-27===edit ==end
		
	}
	
	private void getImages(){
	    String jsonStr = "{total:10,success:'true',images:[{url:'http://e.hiphotos.baidu.com/album/w%3D2048/sign=e6e75f487af40ad115e4c0e3631410df/f7246b600c3387440764470c500fd9f9d72aa019.jpg',target:'http://127.0.0.1:8080/xx.html'},{ url:'http://g.hiphotos.baidu.com/album/w%3D2048/sign=6da27a1d5bafa40f3cc6c9dd9f5c024f/a08b87d6277f9e2f195ad0271e30e924b899f3b6.jpg',target:'http://127.0.0.1:8080/xx.html'}]}";

	    try {
            JSONObject data =new JSONObject(jsonStr);
            if(data != null){
                if(data.get("success").equals("true")){
                    JSONArray dataDetails = data.getJSONArray("images");
                    if(dataDetails != null && dataDetails.length() > 0){
                        for(int i = 0; i < dataDetails.length(); i++){
                            SwitchImageInfo imageInfo = new SwitchImageInfo();
                            imageInfo.setUrl(dataDetails.getJSONObject(i).get("url").toString()); 
                            imageInfo.setTarget(dataDetails.getJSONObject(i).getString("target").toString());
                            images.add(imageInfo);
                        }
                    }
                    
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
	    
	    
	}
	
	

	private void onLoad() {
		mListView.stopRefresh();
		mListView.stopLoadMore();
		mListView.setRefreshTime("刚刚");
	}
	
	
	
	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		items.clear();
		mAdapter.notifyDataSetChanged();
		super.onPause();
		
	}
	
	

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}

	@Override
	public void onResume() {
	    super.onResume();
	    geneItems();
        mAdapter.notifyDataSetChanged();
        //获取接口数据
        getImages();
	};
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.xlistview, null);
//		geneItems();
		mContext=getActivity();
		mListView = (XListView)v.findViewById(R.id.xListView);
		mListView.setPullLoadEnable(true);
		// 设置样式，单列表
		//mAdapter = new ArrayAdapter<String>(getActivity(), R.layout.list_item, items);
		mAdapter = new NewsListAdapter(getActivity(),items,mListView);
		mListView.setAdapter(mAdapter);
		mListView.setXListViewListener(this);
		//===2013-5-27===edit  ===start
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				SharedPreferences prefer=mContext.getSharedPreferences("CurrentSelectedNewId", Context.MODE_PRIVATE);
			    Editor editor=prefer.edit();
			    editor.putString("SecondMenuId",items.get(Integer.valueOf(String.valueOf(arg3))).getId());
			    editor.commit();
				MainActivity main = (MainActivity)getActivity();
				switchFragment(new DetailsFragment(),main);
			}
		});
		
        mViewPager = (ViewPager) v.findViewById(R.id.viewpager);
        mViewPagerAdapter = ViewPagerAdapter.getIntance(mContext, images);
        mViewPager.setAdapter(mViewPagerAdapter);
        mHandler.removeCallbacks(switchRunnable);
        mHandler.postDelayed(switchRunnable, 3000);
		return v;
	}
	
	private void switchFragment(Fragment fragment,MainActivity main) {
		if (main == null)
			return;
		main.switchContent(fragment);
	}
	public void onDestroyView() {
	    super.onDestroyView();
	    mHandler.removeCallbacks(switchRunnable);
	}
	

	
	Runnable switchRunnable = new Runnable() {
        @Override
        public void run() {
            currentItem = (currentItem + 1) % images.size();
            mViewPager.setCurrentItem(currentItem);
            mHandler.postDelayed(this, 3000);
        }
    };
	
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}
	
	private void initSycnGallery() {
		Bitmap image = BitmapFactory.decodeResource(getResources(),
				R.drawable.default_movie_post);
		imagesCache.put("background_non_load", image); // 设置缓存中默认的图片
		initGalleryData();
		imageAdapter = new SycnImageAdapter(urls, getActivity());
		images_ga.setAdapter(imageAdapter);
		images_ga.setSelection(Integer.MAX_VALUE/2);
		images_ga.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				num = arg2;
				Log.i("mahua", "ItemSelected==" + arg2);
				GalleryWhetherStop();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});
	}

	@Override
	public void onRefresh() {
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				start = ++refreshCnt;
				items.clear();
				geneItems();
				// mAdapter.notifyDataSetChanged();
				mAdapter = new NewsListAdapter(getActivity(),items,mListView);
				mListView.setAdapter(mAdapter);
				onLoad();
			}
		}, 2000);
	}

	@Override
	public void onLoadMore() {
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				geneItems();
				mAdapter.notifyDataSetChanged();
				onLoad();
			}
		}, 2000);
	}
	
	
	/**
	 * 判断Gallery滚动是否停止,如果停止则加载当前页面的图片
	 */
	private void GalleryWhetherStop() {
		Runnable runnable = new Runnable() {
			public void run() {
				try {
					int index = 0;
					index = num% urls.size();
					Thread.sleep(1000);
//					if (index == num) {
						url.add(urls.get(index));
						if (index != 0 && urls.get(index - 1) != null) {
							url.add(urls.get(index - 1));
						}
						if (index != urls.size() - 1 && urls.get(index + 1) != null) {
							url.add(urls.get(index + 1));
						}
						Message m = new Message();
						m.what = 1;
						mSycnHandler.sendMessage(m);
//					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		new Thread(runnable).start();
	}
	// 加载图片的异步任务
		class LoadImageTask extends AsyncTask<String, Void, Bitmap> {

			@Override
			protected void onCancelled() {
				// TODO Auto-generated method stub
				super.onCancelled();
			}

			@Override
			protected void onPostExecute(Bitmap result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
			}

			@Override
			protected Bitmap doInBackground(String... params) {
				Bitmap bitmap = null;
				try {
					String url = params[0];
					boolean isExists = Files.compare(url);
					if (isExists == false) {
						Net net = new Net();
						byte[] data = net.downloadResource(mContext, url);
						bitmap = BitmapFactory
								.decodeByteArray(data, 0, data.length);
						imagesCache.put(url, bitmap); // 把下载好的图片保存到缓存中
						Files.saveImage(url, data);
					} else {
						byte[] data = Files.readImage(url);
						bitmap = BitmapFactory
								.decodeByteArray(data, 0, data.length);
						imagesCache.put(url, bitmap); // 把下载好的图片保存到缓存中
					}

					Message m = new Message();
					m.what = 0;
					mSycnHandler.sendMessage(m);

				} catch (Exception e) {
					e.printStackTrace();
				}
				return bitmap;
			}
		}

		private Handler mSycnHandler = new Handler() {
			public void handleMessage(Message msg) {
				try {
					switch (msg.what) {
					case 0: {
						imageAdapter.notifyDataSetChanged();
						break;
					}
					case 1: {
						for (int i = 0; i < url.size(); i++) {
							LoadImageTask task = new LoadImageTask();// 异步加载图片
							task.execute(url.get(i));
							Log.i("mahua", url.get(i));
						}
						url.clear();
					}
					}
					super.handleMessage(msg);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
	
	private void initGalleryData(){
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/f603918fa0ec08fabf7a641659ee3d6d55fbda0d.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/43a7d933c895d143d011bf9273f082025aaf071f.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/63d0f703918fa0ec2ebf584b269759ee3d6ddb7f.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/5ab5c9ea15ce36d31ed8387f3af33a87e850b1a5.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/8601a18b87d6277f6e46217628381f30e924fc2c.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/b48f8c54acf9964c3a29350e.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/bd3eb13533fa828b48da6aabfd1f4134960a5af9.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/29381f30e924b899da3ce5706e061d950a7bf672.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/bd3eb13533fa828b48da6aabfd1f4134960a5af9.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/4bed2e738bd4b31cd73d63fd87d6277f9e2ff877.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/caef76094b36acaf92b619b87cd98d1001e99c24.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/8435e5dde71190efd6154d95ce1b9d16fcfa608a.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/b3de9c824ba1d4cd6d81190f.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/e0fe9925cc2c683834a80f11.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/0bd162d9f2d3572c65911a988a13632762d0c307.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/ac6eddc451da81cb2ac1708a5266d01609243155.jpg");

		urls.add("http://hiphotos.baidu.com/baidu/pic/item/1bd5ad6e8416d98080cb4a48.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/3c6d55fbb2fb43169d0508ca20a4462309f7d36c.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/faedab64034f78f0daf3664a79310a55b2191c8a.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/2fdda3cc7cd98d10b05af088213fb80e7aec90f9.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/b8014a90f603738d9536f39bb31bb051f819ec0f.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/2fdda3cc7cd98d10b05af088213fb80e7aec90f9.jpg");

		urls.add("http://hiphotos.baidu.com/baidu/pic/item/f603918fa0ec08fabf7a641659ee3d6d55fbda0d.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/43a7d933c895d143d011bf9273f082025aaf071f.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/63d0f703918fa0ec2ebf584b269759ee3d6ddb7f.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/5ab5c9ea15ce36d31ed8387f3af33a87e850b1a5.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/8601a18b87d6277f6e46217628381f30e924fc2c.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/b48f8c54acf9964c3a29350e.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/bd3eb13533fa828b48da6aabfd1f4134960a5af9.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/29381f30e924b899da3ce5706e061d950a7bf672.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/bd3eb13533fa828b48da6aabfd1f4134960a5af9.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/4bed2e738bd4b31cd73d63fd87d6277f9e2ff877.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/caef76094b36acaf92b619b87cd98d1001e99c24.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/8435e5dde71190efd6154d95ce1b9d16fcfa608a.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/b3de9c824ba1d4cd6d81190f.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/e0fe9925cc2c683834a80f11.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/0bd162d9f2d3572c65911a988a13632762d0c307.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/ac6eddc451da81cb2ac1708a5266d01609243155.jpg");

		urls.add("http://hiphotos.baidu.com/baidu/pic/item/1bd5ad6e8416d98080cb4a48.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/3c6d55fbb2fb43169d0508ca20a4462309f7d36c.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/faedab64034f78f0daf3664a79310a55b2191c8a.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/2fdda3cc7cd98d10b05af088213fb80e7aec90f9.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/b8014a90f603738d9536f39bb31bb051f819ec0f.jpg");
		urls.add("http://hiphotos.baidu.com/baidu/pic/item/2fdda3cc7cd98d10b05af088213fb80e7aec90f9.jpg");
	}
	
}
	
